<?php

/************************************

EasyCB, Community Forum Software
Copyright (C) 2007, 2008  Jonathon D. Keogh <jonathon.keogh@gmail.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

$Id: inc.func.php 191 2008-05-12 17:06:00Z jonathon.keogh $

************************************/

// Start the output buffer
ob_start();

// Some definitions
define('STATIC_INSTALL', 'static.install.php');
define('INCLUDE_CONFIG', 'inc.config.php');

// Check the configuration file exists
if(!file_exists(INCLUDE_CONFIG))
{
	// If not, redirect to a static page informing about installation
	page_redirect(STATIC_INSTALL);
}

// Try to include the configuration
require INCLUDE_CONFIG;

// Check that appropriate settings are made
if(!isset($config) || !isset($config['db_server']) || !isset($config['db_user']) || !isset($config['db_pass']) || !isset($config['db_name']) || !isset($config['db_prefix']))
{
	// If not, redirect to a static page informing about installation
	page_redirect(STATIC_INSTALL);
}

// Try to connect to the database server
$__db = @mysql_connect($config['db_server'], $config['db_user'], $config['db_pass']) or db_error();

// Select the database
mysql_select_db($config['db_name'], $__db);

// Get all the configuration options from the database
$c = db_query("SELECT `Key`, `Value` FROM `" . config_get("db_prefix") . "config`;");
while($row = db_fetch_assoc($c))
{
	$config[$row['Key']] = $row['Value'];
}

// Check for magic quotes, and remove if they're there
if(get_magic_quotes_gpc())
{
	foreach($_POST as $name => $value)
	{
		$_POST[$name] = stripslashes($value);
	}
	foreach($_GET as $name => $value)
	{
		$_GET[$name] = stripslashes($value);
	}
}

// Run any upgrade
function checkUpgrade($ver)
{
	if(config_get("_upgrdTo_$ver") == 1)
	{
		return true;
	}
	return false;
}

if(!checkUpgrade("1.1"))
{
	db_query("ALTER TABLE `ecb_boards` ADD `Order` INT(3);");
	db_query("ALTER TABLE `ecb_posts` ADD `ReferenceTo` INT(7);");
	db_query("ALTER TABLE `ecb_posts` ADD `EditCount` INT(5);");
	db_query("INSERT INTO `ecb_config` (`Key`, `Value`) VALUES ('_upgrdTo_1.1', '1');");
}

/***

Database functions

***/
function db_error($query="")
{
	global $__db, $config;
	
	// Redirect to the static error page
	page_redirect("static.db-error.php?server=" . urlencode(config_get($config['db_server'])) . "&error=" . urlencode(mysql_error($__db)) . "&query=" . urlencode($query));
}
function db_query($query)
{
	global $__db;
	
	// Perform the query
	$result = mysql_query($query, $__db) or db_error($query);
	
	return $result;
}
function db_fetch_assoc($result)
{
	// Retrieve a row
	$row = mysql_fetch_assoc($result);
	
	return $row;
}
function db_num_rows($result)
{
	// Retrieve the number of rows
	$rows = mysql_num_rows($result);
	
	return $rows;
}
function db_escape($string)
{
	// Escape the string
	$escaped = mysql_escape_string($string);
	
	return $escaped;
}

/***

Configuration functions

***/
function config_get($key)
{
	global $config;
	
	// Pretty simple, just return the key from the array
	return $config[$key];
}
function config_set($key, $value)
{
	global $__db, $config;
	
	// Create the key if it doesn't exist
	if(!config_key_exists($key))
	{
		config_create($key);
	}
	
	// Update the value and the last modified columns
	db_query("UPDATE `" . config_get("db_prefix") . "config` SET `Value`='" . db_escape($value) . "', `LastUpdate`='" . time() . "' WHERE `Key`='" . db_escape($key) . "';");
	
	// Update $config
	$config[$key] = $value;
}
function config_key_exists($key)
{
	global $config;
	
	// If the key is set in the array...
	if(!isset($config[$key]))
	{
		// ...which it isn't, return 0.
		return 0;
	}
	
	// ...which it is, return 1.
	return 1;
}
function config_create($key)
{
	// Run an INSERT query for SQL
	db_query("INSERT INTO `" . config_get("db_prefix") . "config` (`Key`) VALUES ('" . db_escape($key) . "');");
}

/***

User functions

***/
function user_exists($username)
{
	// Perform the existance query
	$r = db_query("SELECT * FROM `" . config_get("db_prefix") . "users` WHERE `Username`='" . db_escape($username) . "';");
	
	// Check the row count
	if(db_num_rows($r) < 1)
	{
		// No rows were found
		return 0;
	}
	
	// Row(s) were found - plural highly unlikely
	return 1;
}
function user_check($username, $password)
{
	// Perform the check query
	$r = db_query("SELECT * FROM `" . config_get("db_prefix") . "users` WHERE `Username`='" . db_escape($username) . "' AND `Password`='" . db_escape($password) . "' AND `Deleted`=0;");
	
	// Check the row count
	if(db_num_rows($r) < 1)
	{
		// No rows were found
		return 0;
	}
	
	// Row(s) were found - plural highly unlikely
	return 1;
}
function user_id($username)
{
	// Perform the query
	$r = db_query("SELECT `ID` FROM `" . config_get("db_prefix") . "users` WHERE `Username`='" . db_escape($username) . "';");
	
	// Check the row count
	if(db_num_rows($r) < 1)
	{
		// No rows were found
		return 0;
	}
	
	// Get data
	$r = db_fetch_assoc($r);
	
	// Return the ID
	return $r['ID'];
}
function user_level($username)
{
	// Perform the query
	$r = db_query("SELECT `Level` FROM `" . config_get("db_prefix") . "users` WHERE `Username`='" . db_escape($username) . "';");
	
	// Check the row count
	if(db_num_rows($r) < 1)
	{
		// No rows were found
		return 0;
	}
	
	// Get data
	$r = db_fetch_assoc($r);
	
	// Return the ID
	return $r['Level'];
}
function user($field, $userid)
{
	// Perform the query
	$r = db_query("SELECT `$field` FROM `" . config_get("db_prefix") . "users` WHERE `ID`='" . db_escape($userid) . "';");
	
	// Check the row count
	if(db_num_rows($r) < 1)
	{
		// No rows were found
		return "";
	}
	
	// Get data
	$r = db_fetch_assoc($r);
	
	// Return the ID
	return $r[$field];
}
function user_name($id)
{
	// Perform the query
	$r = db_query("SELECT `Username` FROM `" . config_get("db_prefix") . "users` WHERE `ID`='" . db_escape($id) . "';");
	
	// Check the row count
	if(db_num_rows($r) < 1)
	{
		// No rows were found
		return config_get("UnknownUser");
	}
	
	// Get data
	$r = db_fetch_assoc($r);
	
	// Return the user name
	return $r['Username'];
}
function user_loggedin()
{
	// Is there any UserID set?
	$userid = sess_get("UserID");
	if($userid == 0)
	{
		// There is no user ID, so we're not logged in
		return 0;
	}
	
	// Check the user still exists
	if(user_exists(user_name($userid)) && user("Deleted", $userid) == 0)
	{
		// They do exist, so they're logged in
		return 1;
	}
	
	// Unset the user's ID
	sess_set("UserID", 0);
	
	// They're not logged in
	return 0;
}

/***

Session functions

***/
if(!isset($_COOKIE['ECBSID']))
{
	// Start a session
	sess_start();
} else {
	// Check the session that we have actually is ours
	if(sess_get("IP", $_COOKIE['ECBSID']) != $_SERVER['REMOTE_ADDR'])
	{
		// It's not ours, start a new one
		sess_start();
	} else {
		// It's ours, change the script settings so that we start using it
		$__sessid = $_COOKIE['ECBSID'];
		
		// Update the LastTime and Where columns
		db_query("UPDATE `" . config_get("db_prefix") . "sessions` SET `LastTime`='" . time() . "', `Where`='" . db_escape(sess_whereAmI()) . "' WHERE `ID`='" . db_escape(sess_id()) . "';");
		
		// Pro-long the cookie
		setcookie('ECBSID', sess_id(), time() + config_get("SessionExpiresAfter"));
		
		// If we're logged in, modify the Last Seen Time
		if(user_loggedin())
		{
			db_query("UPDATE `" . config_get("db_prefix") . "users` SET `LastSeenTime`='" . db_escape(time()) . "', `LastSeenIP`='" . db_escape($_SERVER['REMOTE_ADDR']) . "' WHERE `ID`='" . db_escape(sess_get("UserID")) . "';");
		}
	}
}

function sess_start()
{
	global $__sessid;
	
	// Generate a new session ID
	$__sessid = sess_newID();
	
	// Insert the session in to the sessions table
	db_query("INSERT INTO `" . config_get("db_prefix") . "sessions` (`ID`, `IP`, `Where`, `StartTime`, `LastTime`) VALUES ('" . db_escape($__sessid) . "', '" . db_escape($_SERVER['REMOTE_ADDR']) . "', '" . db_escape(sess_whereAmI()) . "', '" . time() . "', '" . time() . "');");
	
	// Set the cookie so that the client remembers the session
	setcookie('ECBSID', $__sessid, time() + config_get("SessionExpiresAfter"));
}
function sess_whereAmI()
{
	// Return the basename of the page we're on
	return basename($_SERVER['PHP_SELF']);
}
function sess_newID()
{
	// Loop forever until we find an empty one
	while(1)
	{
		// Generate an ID, made up of an MD5 hash
		$id = md5($_SERVER['REMOTE_ADDR'] . rand(0, 10000) . rand(0, 10000));
		
		// If the session doesn't exist, return it as the new ID
		if(!sess_exists($id))
		{
			return $id;
		}
	}
}
function sess_exists($id)
{
	// Perform a query to see if the session exists
	$r = db_query("SELECT * FROM `" . config_get("db_prefix") . "sessions` WHERE `ID`='" . db_escape($id) . "';");
	
	// If there is a row, return 1 - else, 0
	if(db_num_rows($r) > 0)
	{
		return 1;
	}
	
	return 0;
}
function sess_id()
{
	global $__sessid;
	
	// Just return a variable for now
	return $__sessid;
}
function sess_get($column, $id="")
{
	// Was an $id set?
	if($id == "")
	{
		// No, use our own ID
		$id = sess_id();
	}
	
	// Get the column
	$r = db_query("SELECT `" . db_escape($column) . "` FROM `" . config_get("db_prefix") . "sessions` WHERE `ID`='" . db_escape($id) . "';");
	
	// Were any rows returned?
	if(db_num_rows($r) == 0)
	{
		// No, bail out
		return "";
	}
	
	// Get the data
	$r = db_fetch_assoc($r);
	
	// Return the column
	return $r[$column];
}
function sess_set($column, $value, $id="")
{
	// Was an $id set?
	if($id == "")
	{
		// No, use our own ID
		$id = sess_id();
	}
	
	// Modify the column
	$r = db_query("UPDATE `" . config_get("db_prefix") . "sessions` SET `" . db_escape($column) . "`='" . db_escape($value) . "' WHERE `ID`='" . db_escape($id) . "';");
}

/***

Board functions

***/
function board_exists($boardid)
{
	// Perform a query to see if the board exists
	$r = db_query("SELECT * FROM `" . config_get("db_prefix") . "boards` WHERE `ID`='" . db_escape($boardid) . "';");
	
	// If there is a row, return 1 - else, 0
	if(db_num_rows($r) > 0)
	{
		return 1;
	}
	
	return 0;
}
function board_lastPost($id)
{
	// Perform the query to get the post
	$post = db_query("SELECT `UserID`, `Time`, `ID`, `TopicID` FROM `" . config_get("db_prefix") . "posts` WHERE `ID`='" . db_escape($id) . "';");
	
	// Is there a row?
	if(db_num_rows($post) < 1)
	{
		// No, return a space
		return "&nbsp;";
	}
	
	// Yes, get the data for the row
	$post = db_fetch_assoc($post);
	
	// Return the data (formatted)
	return (user("Deleted", $post['UserID']) == 0 ? "<a href=\"page.user.php?id=" . urlencode($post['UserID']) . "\">" . htmlentities(user_name($post['UserID'])) . "</a>" : htmlentities(user_name($post['UserID']))) . " <a href=\"page.topic.php?id=" . urlencode($post['TopicID']) . "#response-" . urlencode($post['ID']) . "\">&raquo;</a><br>" . date(config_get("DateString"), $post['Time']);
}
function board_parent($id)
{
	// Perform the query to get the parent board
	$b = db_query("SELECT `Parent` from `" . config_get("db_prefix") . "boards` WHERE `ID`='" . db_escape($id) . "';");
	
	// Is there a row?
	if(db_num_rows($b) < 1)
	{
		// No, return zero
		return 0;
	}
	
	// Get the data
	$b = db_fetch_assoc($b);
	
	// Return the ID
	return $b['Parent'];
}
function board_label($id)
{
	// Perform the query to get the board label
	$b = db_query("SELECT `Label` from `" . config_get("db_prefix") . "boards` WHERE `ID`='" . db_escape($id) . "';");
	
	// Is there a row?
	if(db_num_rows($b) < 1)
	{
		// No, return blank
		return "";
	}
	
	// Get the data
	$b = db_fetch_assoc($b);
	
	// Return the ID
	return $b['Label'];
}
function board_trail($id)
{
	$boards = Array();
	$c = $id;
	while(1)
	{
		$b = board_parent($c);
		$boards[$b] = $c;
		if($b == 0)
		{
			break;
		}
		$c = $b;
	}
	$x = "0";
	while(1)
	{
		if($boards[$c] == 0)
		{
			break;
		}
		$x .= "|" . $boards[$c];
		if($boards[$c] == $topic['Board'])
		{
			break;
		}
		$c = $boards[$c];
	}
	return $x;
}

/***

Page functions

***/
function page_redirect($url)
{
	// End the output buffer
	ob_clean();
	
	// Send the HTTP headers for a relocation
	header('HTTP/1.1 302 Found');
	header('Location: ' . $url);
	
	// Send some text in case the browser is real old
	print "<HTML>\n";
	print "<P><A HREF=\"" . htmlentities($url) . "\">Click here</A> to continue.</P>\n";
	print "</HTML>\n";
	
	// Exit
	exit;
}
function page_header($title, $showHeader=true)
{
	global $adminArea;
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>

<head>
<title><?=htmlentities(config_get("BoardName")) ?><?=$title == "" ? "" : ": $title" ?></title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<style type="text/css">
<!--

<?php

/***** OLD THEME *****

table, body { font-family: Tahoma; font-size: 10pt; }
body { color: #FFFFFF; background-color: #000000; }
a { color: #FFFFFF; text-decoration: underline; }

.section_table { background-color: #5C5C5C; }
.section_row_title {}
.section_row_text {}
.section_cell_title { background-color: #A1A1A1; padding: 5px; }
.section_cell_text { padding: 5px; }

***** OLD THEME *****/

?>

table, body { font-family: sans-serif; font-size: 10pt; }
body { color: #000000; background-color: #FFFFFF; }
a { color: #0000FF; text-decoration: underline; }

.section_table { background-color: #CCCCCC; }
.section_row_title {}
.section_row_text {}
.section_cell_title { background-color: #A1A1A1; padding: 5px; }
.section_cell_text { padding: 5px; }

.referquote { padding: 5px; border-width: 1px; border-color: #000000; border-style: solid; background-color: #BBBBBB; width: 488px; }
.referquote2 { padding: 5px; border-width: 1px; border-color: #000000; border-style: solid; background-color: #BBBBBB; width: 100%; }

.wsection_table { background-color: pink; }
.wsection_row_title {}
.wsection_row_text {}
.wsection_cell_title { padding: 5px; }
.wsection_cell_text { padding: 5px; }

form { margin: none; }

//-->
</style>
<script language="javascript" type="text/javascript">
<!--

originalTopic = "<?=addslashes($title == "" ? "" : "$title") ?>";
function changeTitle(newTitle)
{
	if(newTitle == "")
	{
		newTitle = originalTopic;
	}
	document.title = "<?=addslashes(htmlentities(config_get("BoardName"))) ?>: " + newTitle;
	document.getElementById('title').innerHTML = newTitle;
}

//-->
</script>
</head>

<body>

<?php

if($showHeader)
{
?>
<table width="100%" cellspacing="0" cellpadding="0">
	<tr>
		<td width="200"><img src="img/forum-logo.jpg" alt="Easy Community - EasyCB"></td>
		<td><b style="font-size: 20pt;" id="title"><?=$title == "" ? htmlentities(config_get("BoardName")) : $title ?></b><br>
	<a href="page.boards.php">Boards list</a> - <a href="page.member-list.php">Member list</a> -
<?php

if(user_loggedin())
{
?>
Hello, <?=htmlentities(user_name(sess_get("UserID"))) ?> - <a href="page.logout.php">Logout</a>
<?php
	if(user_level(user_name(sess_get("UserID"))) == 2)
	{
		print " - <a href=\"page.admin.php\">Administration</a>";
	}
} else {
?>
<a href="page.register.php">Register</a> - <a href="page.login.php">Log in</a>
<?php
}
?></td>
	</tr>
</table>
<hr>

<?php
	if($adminArea == true)
	{
		print "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\">\n";
		print "<tr>\n";
		print "<td valign=\"top\" style=\"padding-right: 5px;\" width=\"200\">";
		
		page_section("Administration tasks");
		print "<a href=\"page.admin.boards.php\">Boards</a><br>\n";
		print "<a href=\"page.admin.config.php\">Configuration</a><br>\n";
		print "<a href=\"page.admin.users.php\">Users</a><br>\n";
		print "<br>\n";
		print "<a href=\"page.admin.reset-stats.php\">Reset Statistics</a><br>\n";
		page_section();
		
		print "</td>\n";
		print "<td valign=\"top\">\n";
	}
	}
}
function page_footer($svnid, $showFooter=true)
{
	global $adminArea;
	
	if($adminArea == true)
	{
		print "</td>\n";
		print "</td>\n";
		print "</table>\n";
	}
	
	if($showFooter)
	{
?>

<p align="center"><small><?=$svnid ?><br>
	$Id: inc.func.php 191 2008-05-12 17:06:00Z jonathon.keogh $<br>
	<a href="page.rules.php">Forum rules</a> | <a href="page.credits.php">About EasyCB</a></small></p>

<?php
	}
	
?>

</body>

</html>
<?php
}
$__section_is_open = false;
function page_section($title="", $w=false)
{
	global $__section_is_open;
	
	$w = ($w ? "w" : "");
	
	if(!$__section_is_open)
	{
		$__section_is_open = true;
?>

<table width="100%" class="<?=$w ?>section_table">
<?php

if($title != "")
{
?>
<tr class="<?=$w ?>section_row_title"><td class="<?=$w ?>section_cell_title"><b><?=$title ?></b></td></tr>
<?php
}

?>
<tr class="<?=$w ?>section_row_text"><td class="<?=$w ?>section_cell_text"><?php
	} else {
		$__section_is_open = false;
?></td></tr>
</table>
<br>

<?php
	}
}
function nl2br2($text)
{
	return str_replace("<br />", "<br>", nl2br($text));
}

// Are we in the administration area?
$__b = basename($_SERVER['PHP_SELF']);
$adminArea = false;
if(substr($__b, 0, 10) == "page.admin" && user_loggedin() && user_level(user_name(sess_get("UserID"))) == 2)
{
	$adminArea = true;
}

?>